//
//  ZLOuthorViewController.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/22.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import UIKit
import SVProgressHUD

//通过webview加载新浪微博授权界面
class ZLOuthorViewController: UIViewController {

    private lazy var webView = UIWebView()
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
        
        //view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        //设置导航栏
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontsize: 14, target: self, action: #selector(closeCV), isBackButton: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        

    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //加载授界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(ZLAPPKEY)&redirect_uri=\(ZLRedirectUrl)"
        
        guard let url = URL(string: urlString)else{
            
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
        ////////
        //使用授权码code 换区token
        /*ZLNetWorkManager.shared.loadAccessToken(code: "87fcdd0df0e43a64e319c0e8aa559982") { (isSuccess) in
            
            if !isSuccess{
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }
            else
            {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZLUserLonginSuccessNotification), object: nil)
                
                self.closeCV()
            }
        }*/
        /////////
        
    }

    @objc fileprivate func closeCV(){
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    //js 注入
    @objc private func autoFill(){
        
        //准备js
        let js = "document.getElementById('userId').value = '18220736955';" + "document.getElementById('passwd').value = 'aini328405320';"
        
        
        //执行js
        webView.stringByEvaluatingJavaScript(from: js)
        
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}

extension ZLOuthorViewController: UIWebViewDelegate
{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("------\(request.url?.absoluteString)")
        //如果请求地址包含www。baidu.com  不加载页面
        if (request.url?.absoluteString.hasPrefix(ZLRedirectUrl)) == false{
            
            
            return true
            
        }
        //从地址中查找code
        //如果有code说明授权成功 否则授权失败
        print("------\(request.url?.absoluteString)")
        //url中的请求参数
        print("加载请求--\(request.url?.query)")
        if (request.url?.query?.hasPrefix("code=") == false){
            
            print("授权取消")
            
            closeCV()
            
            return false
        }
        //从query字符串中取出授权码code
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        //使用授权码code 换区token
        ZLNetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess{
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }
            else
            {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZLUserLonginSuccessNotification), object: nil)
                
                self.closeCV()
            }
        }
        
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
}
